package com.kx.game.center.utils;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class IPUtils {
	public static int getIntIP(String ip) throws UnknownHostException {
		Inet4Address a = (Inet4Address) InetAddress.getByName(ip);
		byte[] b = a.getAddress();
		int i = ((b[0] & 0xFF) << 24) | ((b[1] & 0xFF) << 16) | ((b[2] & 0xFF) << 8) | ((b[3] & 0xFF) << 0);
		return i;
	}

	public static boolean checkIP(String subnetWithMask, String ip) throws UnknownHostException {
		int subnet = 0;
		int bits = 0;
		int ipint = getIntIP(ip);
		if (subnetWithMask.contains("/")) {
			subnet = getIntIP(subnetWithMask.split("/")[0]);
			bits = Integer.parseInt(subnetWithMask.split("/")[1]);
		} else {
			subnet = getIntIP(subnetWithMask);
		}
		
		if(subnet == 0){
			return true;
		}

		int mask = -1 << (32 - bits);
		return (subnet & mask) == (ipint & mask);
	}

	public static void main(String[] args) throws UnknownHostException {
		System.out.println(checkIP("10.0.0.0/16", "10.10.11.5"));
	}
}
